from fastapi import APIRouter, Request
from crypto_utils import encrypt_token
from utils import create_json_response

router = APIRouter()

@router.post("/bind")
async def bind_device(request: Request):
    """设备绑定接口 - 接收原始数据流并写入文件"""
    # 读取原始数据流
    body = await request.body()
    
    # 将原始数据写入111.txt
    with open("111.txt", "wb") as f:
        f.write(body)
    
    # 如果需要解析表单数据
    form_data = await request.form()
    if form_data:
        with open("111.txt", "a", encoding="utf-8") as f:
            f.write("\n--- 解析后的表单数据 ---\n")
            for key, value in form_data.items():
                f.write(f"{key}: {value}\n")
    
    # 使用与login.py相同的token生成逻辑
    username = "13800138000"
    password = "123456"
    login_data = f"{username}:{password}"
    token = encrypt_token(login_data)
    
    response_data = {
        "error": "",  # 当需要踢下线时设置错误信息
        "token": token
    }
    
    return create_json_response(response_data)